<?php

namespace App\Http\Controllers\Admin;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use	Image;
use	App\CommonSettings;
use	App\MailSettings;
use	App\Navs;
use	App\Cates;
use	App\Links;
use App\ArticleCates;
use Mail;

class SettingController extends Controller
{

	
	public $pageSize = null;
	
	
	public function __construct()
	{
		$this->pageSize	 = CS('admin_page_size')!=''?CS('admin_page_size'):20;
	}

	/**
	 *	通用设置
	 */
	public function index(Request $req)
	{
		//权限验证
		if(!in_array('common_setting',session('access')))
		{
			return redirect()->action('Admin\IndexController@tips',['sec'=>'3','act'=>'fail',
				'info' => trans('admin.access_fail'),
				'url' => url('admin/info')
			]);
		}

		
		$sets	= CommonSettings::where('id',1)->first();

		if($req->isMethod('get'))
		{
			$title 	= trans('admin.common_setting');
			
			return view('admin.setting.common_setting',[
				'title'		=> 	$title,
				'sets'		=> 	$sets,
			]);	
		}
		else
		{
			$input = Input::except('MAX_FILE_SIZE','_token');
			//验证字段
	        $rule = [
	            'site_name'			=> 'required|max:255',
	            'site_keywords'		=> 'max:255',
	            'site_desc'			=> 'max:255',
	            'icp'				=> 'max:255',
				'logo'				=> 'mimes:jpeg,jpg,png',
				'front_page_size'	=> 'required|integer',
				'admin_page_size'	=> 'required|integer',
				'watermark'			=> 'mimes:jpeg,jpg,png',
				'wm_switch'			=> 'in:0,1',
				'telephone'			=> 'max:255',
				'qq'				=> 'max:255',
				'email'				=> 'email',
				'com_name'			=> 'max:255',
				'address'			=> 'max:255',
				'notice'			=> 'max:255',
	        ];
			
	        $message = [
	            'site_name.required'		=> 	'网站名称是必须的',
				'site_name.max' 			=> 	'网站名称长度不能大于255',
				'site_keywords.max' 		=> 	'SEO关键字长度不能大于255',
				'site_desc.max' 			=> 	'网站描述长度不能大于255',
				'icp.max' 					=> 	'ICP备案号长度不能大于255',
	            'logo.mimes'				=>  '仅支持格式为jpeg,jpg,png的图片',
	            'front_page_size.required'	=>	'分页是必须的',	
				'front_page_size.integer'	=>  '前台分页为整数',
				'admin_page_size.required'	=>	'分页是必须的',
				'admin_page_size.integer'	=>  '后台分页为整数',	
	            'watermark.mimes'			=>  '仅支持格式为jpeg,jpg,png的图片',	
	            'wm_switch.in'				=>  '请选择是或否',
	            'telephone.max'				=> 	'电话长度不能大于255',
	            'qq.max'					=> 	'qq长度不能大于255',
	            'email.email'				=> 	'邮箱格式错误',
	            'com_name.max'				=> 	'公司名称长度不能大于255',
	            'address.max'				=> 	'地址长度不能大于255',
	            'notice.max'				=> 	'公告长度不能大于255',

	        ];
			
	        $validate = Validator::make($input,$rule,$message);
	        if($validate->fails())
	        {
	            return back()-> withErrors($validate)->withInput($req->all());
	        }
			
			//logo图片处理
			if(isset($input['logo']))
			{
				
				if($sets -> logo != '')
				{
					unlink(public_path($sets -> logo));
				}
								
				$path = 'uploads/settings/'.date('Y/');
				if(!is_dir($path))
				{
					mkdir($path,0777,true);
				}
				
				$img_ori	= Image::make($input['logo']);
		        $_logoOriPath  	= $path.rand(1111,9999).'_logo_'.strRand(4).'.jpg';
				$img_ori->save($_logoOriPath );
				CommonSettings::where('id',1)
				->update([
					'logo'				=> $_logoOriPath,
				]);
			}
			
			//水印图片处理
			if(isset($input['watermark']))
			{
				if($sets -> watermark != '')
				{
					unlink(public_path($sets -> watermark));
				}
								
				$path = 'uploads/settings/'.date('Y/');
				if(!is_dir($path))
				{
					mkdir($path,0777,true);
				}
				
				$img_ori	= Image::make($input['watermark']);
		        $_wmOriPath  = $path.rand(1111,9999).'_wm_'.strRand(4).'.png';
				$img_ori->save($_wmOriPath);
				CommonSettings::where('id',1)
				->update([
					'watermark'			=> $_wmOriPath,
				]);			
			}
			
			CommonSettings::where('id',1)
			->update([
	            'site_name'			=> trim($req->site_name),
	            'site_keywords'		=> trim($req->site_keywords),
	            'site_desc'			=> trim($req->site_desc),
	            'icp'				=> trim($req->icp),
				'front_page_size'	=> trim($req->front_page_size),
				'admin_page_size'	=> trim($req->admin_page_size),
				'wm_switch'			=> trim($req->wm_switch),
				'telephone'			=> trim($req->telephone),
				'qq'				=> trim($req->qq),
				'email'				=> trim($req->email),
				'com_name'			=> trim($req->com_name),
				'address'			=> trim($req->address),
				'notice'			=> trim($req->notice),
			]);
			
			return redirect()->action('Admin\IndexController@tips',['sec'=>'3','act'=>'update_succ',
				'info' => trans('admin.update_succ'),
				'url' => url('admin/info')
			]);
		}
		
	}


	/**
	 *	邮件设置 
	 */
	public function email(Request $req)
	{
		//权限验证
		if(!in_array('mail_setting',session('access')))
		{
			return redirect()->action('Admin\IndexController@tips',['sec'=>'3','act'=>'fail',
				'info' => trans('admin.access_fail'),
				'url' => url('admin/info')
			]);
		}

		
		$sets	= MailSettings::where('id',1)->first();

		if($req->isMethod('get'))
		{
			$title 	= trans('admin.email_setting');
	
			return view('admin.setting.email_setting',[
				'title'		=> 	$title,
				'sets'		=> 	$sets,
			]);	
		}
		else
		{
			$input = Input::except('MAX_FILE_SIZE','_token');
	
			//验证字段
	        $rule = [
	            'host'			=> 'required|max:255',
	            'port'			=> 'integer',
	            'encrytion'		=> 'in:ssl,tls',
	            'username'		=> 'required|max:255',
	            'password'			=> 'required|max:255',

	        ];
			
	        $message = [
	            'host.required'		=> 	'服务器地址是必须的',
				'host.max' 			=> 	'服务器地址长度不能大于255',
				'encrytion.in'		=>	'请选择加密方式',
				'port.integer'		=>  '端口为数字',
				'username.required'		=> 	'用户名是必须的',
				'username.max' 			=> 	'用户名地址长度不能大于255',
				'password.required'		=> 	'密码是必须的',
				'password.max' 			=> 	'密码地址长度不能大于255',
	        ];
			
			
			
	        $validate = Validator::make($input,$rule,$message);
	        if($validate->fails())
	        {
	            return back()-> withErrors($validate)->withInput($req->all());
	        }
			
			MailSettings::where('id',1)
			->update([
	            'host'			=> trim($req->host),
	            'encrytion'			=> trim($req->encrytion),
	            'port'				=> trim($req->port),
	            'username'			=> trim($req->username),
	            'password'			=> trim($req->password),
			]);
			
			return redirect()->action('Admin\IndexController@tips',['sec'=>'3','act'=>'update_succ',
				'info' => trans('admin.update_succ'),
				'url' => url('admin/info')
			]);
			
		}

	}


	/**
	 * 邮件发送测试 
	 */
	public function emailTest(Request $req)
	{
		//权限验证
		if(!in_array('mail_test',session('access')))
		{
			return redirect()->action('Admin\IndexController@tips',['sec'=>'3','act'=>'fail',
				'info' => trans('admin.access_fail'),
				'url' => url('admin/info')
			]);
		}
		
		if($req->isMethod('get'))
		{
			$title 	= trans('admin.email_test');
	
			return view('admin.setting.mail_test',[
				'title'		=> 	$title,
			]);	
		}
		else
		{
			$input = Input::except('MAX_FILE_SIZE','_token');
			//验证字段
	        $rule = [
	            'sender'		=> 'required|max:50',
	            'title'			=> 'max:80',
	            'to'			=> 'required|email',
	            'content'		=> 'required',
	        ];
			
	        $message = [
	            'sender.required'		=> 	'发送者是必须的',
				'sender.max' 			=> 	'发送者长度不能大于50',
				'title.max' 			=> 	'主题长度不能大于50',
	            'to.required'			=> 	'目标邮箱是必须的',
	            'to.email'				=> 	'目标邮箱格式不正确',
	            'content.required'		=> 	'邮件内容不能为空',
	            
	        ];
	        $validate = Validator::make($input,$rule,$message);
	        if($validate->fails())
	        {
	            return back()-> withErrors($validate)->withInput($req->all());
	        }
			
			//设置邮箱发送配置
			config([
				'mail.host' 		=>	MS('host'),
				'mail.encryption'	=>  MS('encrytion'),
				'mail.port'			=> 	MS('port'),
				'mail.username'		=> 	MS('username'),
				'mail.password'		=> 	MS('password'),
			]);
			
			
			Mail::raw($req->content,function ($message) use ($req) {
				$message->subject(trim($req->title));
				$message->from(MS('username'),trim($req->sender));
				$message->to($req->to);
				return $message->getSwiftMessage();
			});
			
			
			return redirect()->action('Admin\IndexController@tips',[
				'sec'	=>	'5',
				'act'	=>	'update_succ',
				'info' 	=>	trans('admin.send_succ'),
				'url' 	=> 	url('admin/info')
			]);
			
		}
		
	}
	
	
	/**
	 * 导航栏列表
	 */
	public function nav(Request $req)
	{
		//权限验证
		if(!in_array('nav_list',session('access')))
		{
			return redirect()->action('Admin\IndexController@tips',[
				'sec'	=>'3',
				'act'	=>'fail',
				'info' 	=> trans('admin.access_fail'),
				'url' 	=> url('admin/info')
			]);
		}	
		
		$title 		= 	trans('admin.nav_list');
		$data		= 	Navs::all();
		return view('admin.setting.nav',['title'=>$title,
			'data'		=>	$data,
		]);
	}




	/**
	 * 导航栏添加
	 */
	public function navAdd(Request $req)
	{
		//权限验证
		if(!in_array('nav_add',session('access')))
		{
			return redirect()->action('Admin\IndexController@tips',[
				'sec'	=>'3',
				'act'	=>'fail',
				'info' 	=> trans('admin.access_fail'),
				'url' 	=> url('admin/info')
			]);
		}	
		
		if($req->isMethod('get'))
		{
			$title 		= 	trans('admin.nav_add');
			$data		= 	Navs::all();
			return view('admin.setting.nav_add',[
				'title'	=>	$title,
				'cates'		=> 	(new Cates)->getTree((new Cates)->getAllCates()),
				'artcates'	=> 	(new ArticleCates)->getTree((new ArticleCates)->getAllCates()),
				
			]);	
		}
		else if($req->isMethod('post'))
		{
			$input = Input::except('MAX_FILE_SIZE','_token');
			//验证字段
	        $rule = [
	            'nav_name' 	=> 'required|max:100',
	            'url'    	=> 'required',
	            'is_show'    	=> 'required|in:0,1',
	            'is_hot'    	=> 'required|in:0,1',
	            'is_blank'    	=> 'required|in:0,1',
	            'sort_order'   	=> 'integer',
	        ];
	        $message = [
	            'nav_name.required' => '导航名称不能为空',
				'nav_name.max' 	 	=> '导航名称长度不能大于100',
	            'url.required' 		=> 'Url不能为空',
				'is_show.required'  => '请选择是否显示',
				'is_show.in'  		=> '请选择是否显示',
				'is_hot.required'  	=> '请选择是否推荐',
				'is_hot.in'  		=> '请选择是否推荐',	
				'is_blank.required'  	=> '请选择打开窗口',
				'is_blank.in'  			=> '请选择打开窗口',
				'sort_order.integer'=> '排序为整数',

	        ];
	
	        $validate = Validator::make($input,$rule,$message);
	        if($validate->fails())
	        {
	            return back()-> withErrors($validate)->withInput($req->all());
	        }
			
			Navs::insert([
				'nav_name'		=> trim($req->nav_name),
				'url'			=> trim($req->url),
				'is_show'		=> trim($req->is_show),
				'is_hot'		=> trim($req->is_hot),
				'is_blank'		=> trim($req->is_blank),
				'sort_order'	=> trim($req->sort_order),
			]);
			
			return redirect()->action('Admin\IndexController@tips',[
				'sec'	=>	'3',
				'act'	=>	'succ',
				'info' 	=>	trans('admin.add_succ'),
				'url' 	=> 	url('admin/nav')
			]);	
		}
	}




	/**
	 * 导航栏修改
	 */
	public function navUpdate(Request $req,$id)
	{
		//权限验证
		if(!in_array('nav_edit',session('access')))
		{
			return redirect()->action('Admin\IndexController@tips',[
				'sec'	=>'3',
				'act'	=>'fail',
				'info' 	=> trans('admin.access_fail'),
				'url' 	=> url('admin/info')
			]);
		}	
		
		if(Navs::where('nav_id',$id)->count() < 1)
		{
			return redirect('admin/nav');
		}
		
		if($req->isMethod('get'))
		{
			$title 		= 	trans('admin.nav_edit');
			$data		= 	Navs::all();
			return view('admin.setting.nav_update',[
				'title'	=>	$title,
				'cates'		=> 	(new Cates)->getTree((new Cates)->getAllCates()),
				'artcates'	=> 	(new ArticleCates)->getTree((new ArticleCates)->getAllCates()),
				'nav'		=> 	Navs::where('nav_id',$id)->first(),
			]);	
		}
		else if($req->isMethod('post'))
		{
			$input = Input::except('MAX_FILE_SIZE','_token');
			//验证字段
	        $rule = [
	            'nav_name' 	=> 'required|max:100',
	            'url'    	=> 'required',
	            'is_show'    	=> 'required|in:0,1',
	            'is_hot'    	=> 'required|in:0,1',
	            'is_blank'    	=> 'required|in:0,1',
	            'sort_order'   	=> 'integer',

	        ];
	        $message = [
	            'nav_name.required' => '导航名称不能为空',
				'nav_name.max' 	 	=> '导航名称长度不能大于100',
	            'url.required' 		=> 'Url不能为空',
				'is_show.required'  => '请选择是否显示',
				'is_show.in'  		=> '请选择是否显示',
				'is_hot.required'  	=> '请选择是否推荐',
				'is_hot.in'  		=> '请选择是否推荐',
				'is_blank.required'  	=> '请选择打开窗口',
				'is_blank.in'  			=> '请选择打开窗口',
				'sort_order.integer'=> '排序为整数',

	        ];
	
	        $validate = Validator::make($input,$rule,$message);
	        if($validate->fails())
	        {
	            return back()-> withErrors($validate)->withInput($req->all());
	        }
			
			Navs::where('nav_id',$id)
			->update([
				'nav_name'		=> trim($req->nav_name),
				'url'			=> trim($req->url),
				'is_show'		=> trim($req->is_show),
				'is_hot'		=> trim($req->is_hot),
				'is_blank'		=> trim($req->is_blank),
				'sort_order'	=> trim($req->sort_order),
			]);
			
			return redirect()->action('Admin\IndexController@tips',[
				'sec'	=>	'3',
				'act'	=>	'succ',
				'info' 	=>	trans('admin.update_succ'),
				'url' 	=> 	url('admin/nav')
			]);	
		}
	}
	

	/**
	 * 导航栏删除
	 */
	public function navDel($id)
	{
		//权限验证
		if(!in_array('nav_del',session('access')))
		{
			return redirect()->action('Admin\IndexController@tips',[
				'sec'	=>'3',
				'act'	=>'fail',
				'info' 	=> trans('admin.access_fail'),
				'url' 	=> url('admin/info')
			]);
		}	
		
		if(Navs::where('nav_id',$id)->count() < 1)
		{
			return redirect('admin/nav');
		}

		Navs::where('nav_id',$id)->delete();
		
		return redirect('admin/nav');
	}
	
	
	
	/**
	 * 友情链接列表
	 */
	public function link(Request $req)
	{
		//权限验证
		if(!in_array('link_list',session('access')))
		{
			return redirect()->action('Admin\IndexController@tips',[
				'sec'	=>'3',
				'act'	=>'fail',
				'info' 	=> trans('admin.access_fail'),
				'url' 	=> url('admin/info')
			]);
		}
	
		$title 		= 	trans('admin.link_list');
		$data		= 	Links::paginate($this -> pageSize);
	
		return view('admin.setting.link_list',['title'=>$title,
			'data'		=>	$data,
		]);
	
	}


	/**
	 * 友情链接添加
	 */
	public function linkAdd(Request $req)
	{
		//权限验证
		if(!in_array('link_add',session('access')))
		{
			return redirect()->action('Admin\IndexController@tips',[
				'sec'	=>'3',
				'act'	=>'fail',
				'info' 	=> trans('admin.access_fail'),
				'url' 	=> url('admin/info')
			]);
		}

		if($req->isMethod('get'))
		{
			$title  = trans('admin.link_add');
			return view('admin.setting.link_add',[
				'title'=>$title,
			]);			
		}
		else if($req->isMethod('post'))
		{
			$input = Input::except('MAX_FILE_SIZE','_token');
			//验证字段
	        $rule = [
	            'link_name' 	=> 'required|max:100',
	            'url'    	    => 'required',
	            'is_show'    	=> 'required|in:0,1',
	            'sort_order'   	=> 'integer',

	        ];
	        $message = [
	            'link_name.required' 	=> '链接名称不能为空',
				'link_name.max' 	 	=> '链接名称长度不能大于100',
	            'url.required' 		=> 'Url不能为空',
				'is_show.required'  => '请选择是否显示',
				'is_show.in'  		=> '请选择是否显示',
				'sort_order.integer'=> '排序为整数',
	        ];		
	        $l_id	=  Links::insertGetId([
	        	'link_name' => trim($req->link_name),
	        	'url' 		=> 'http://'.getUrl(trim($req->url)),
	        	'is_show' 		=> trim($req->is_show),
	        	'sort_order' 	=> trim($req->sort_order),
	      	]);
	        	
			//logo处理
			if(isset($input['logo']))
			{				
				$path = 'uploads/links/'.date('Y/m/');
				if(!is_dir($path))
				{
					mkdir($path,0777,true);
				}
				
				$img_ori	= Image::make($input['logo'])->resize(120,50);
		        $_oriPath  	= $path.rand(1111,9999).'_'.strRand(4).'.jpg';
				$img_ori->save($_oriPath);
				
				Links::where('l_id',$l_id)
				->update(['logo' => $_oriPath]);				
			}
			
			return redirect()->action('Admin\IndexController@tips',[
				'sec'	=> '3',
				'act'	=> 'succ',
				'info' 	=> trans('admin.add_succ'),
				'url' 	=> url('admin/link')
			]);
		}
	}



	/**
	 * 友情链接添加
	 */
	public function linkUpdate(Request $req,$id)
	{
		//权限验证
		if(!in_array('link_edit',session('access')))
		{
			return redirect()->action('Admin\IndexController@tips',[
				'sec'	=>'3',
				'act'	=>'fail',
				'info' 	=> trans('admin.access_fail'),
				'url' 	=> url('admin/info')
			]);
		}
		
		if(Links::where('l_id',$id)->count() < 1)
		{
			return redirect('admin/link');
		}
		
		$link	= Links::where('l_id',$id)->first();
		
		if($req->isMethod('get'))
		{
			$title  = trans('admin.link_add');
			return view('admin.setting.link_update',[
				'title'		=>	$title,
				'link'		=> 	$link
			]);			
		}
		else if($req->isMethod('post'))
		{
			$input = Input::except('MAX_FILE_SIZE','_token');
			//验证字段
	        $rule = [
	            'link_name' 	=> 'required|max:100',
	            'url'    	    => 'required',
	            'is_show'    	=> 'required|in:0,1',
	            'sort_order'   	=> 'integer',

	        ];
	        $message = [
	            'link_name.required' 	=> '链接名称不能为空',
				'link_name.max' 	 	=> '链接名称长度不能大于100',
	            'url.required' 		=> 'Url不能为空',
				'is_show.required'  => '请选择是否显示',
				'is_show.in'  		=> '请选择是否显示',
				'sort_order.integer'=> '排序为整数',
	        ];		
	        Links::where('l_id',$id)
	        ->update([
	        	'link_name' => trim($req->link_name),
	        	'url' 		=> 'http://'.getUrl(trim($req->url)),
	        	'is_show' 		=> trim($req->is_show),
	        	'sort_order' 	=> trim($req->sort_order),
	      	]);
	        	
			//logo处理
			if(isset($input['logo']))
			{
				if($link -> logo != '')
				{
					unlink(public_path($link -> logo));
				}
				
				$path = 'uploads/links/'.date('Y/m/');
				if(!is_dir($path))
				{
					mkdir($path,0777,true);
				}
				
				$img_ori	= Image::make($input['logo'])->resize(120,50);
		        $_oriPath  	= $path.rand(1111,9999).'_'.strRand(4).'.jpg';
				$img_ori->save($_oriPath);
				
				Links::where('l_id',$id)
				->update(['logo' => $_oriPath]);				
			}
			
			return redirect()->action('Admin\IndexController@tips',[
				'sec'	=> '3',
				'act'	=> 'succ',
				'info' 	=> trans('admin.update_succ'),
				'url' 	=> url('admin/link')
			]);
		}
	}



	/**
	 * 友情链接删除
	 */
	public function linkDel($id)
	{
		//权限验证
		if(!in_array('link_del',session('access')))
		{
			return redirect()->action('Admin\IndexController@tips',[
				'sec'	=>'3',
				'act'	=>'fail',
				'info' 	=> trans('admin.access_fail'),
				'url' 	=> url('admin/info')
			]);
		}
		
		if(Links::where('l_id',$id)->count() < 1)
		{
			return redirect('admin/link');
		}
		
		$link	= Links::where('l_id',$id)->first();
		
		if($link -> logo != '')
		{
			unlink(public_path($link -> logo));
		}
		
		Links::where('l_id',$id)->delete();
		
		return redirect('admin/link');
	}

}